package com.lv.suyiyong.hfr.ui

import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lv.common.base.BaseActivity
import com.lv.common.dialog.SwipeCatpchaDialog
import com.lv.common.im.GenerateTestUserSig
import com.lv.common.im.push.OfflineMessageDispatcher
import com.lv.common.imp.OnDialogSureListener
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.network.model.DataResult
import com.lv.common.thirdparty.ShareUtils
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.LiveEventUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.TimerUnit
import com.lv.common.utils.YgxNetUtilsKt
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.YgxUtilsKt.Companion.sendCode
import com.lv.common.utils.showToast
import com.lv.common.widget.textview.SpanTextView
import com.lv.service.bean.AroutBean
import com.lv.service.event.ThreeLandingEvent
import com.lv.service.model.EditorViewModel
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.LoginByCodeReqBody
import com.lv.service.net.SendCodeBody
import com.lv.service.net.ThreedLoginReqBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.utils.YgxAroutPageKt
import com.lv.service.webview.ConsealWebActivity
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.bean.TokenBean
import com.lv.suyiyong.hfr.databinding.ActivityLoginBinding
import com.tencent.qcloud.tuicore.TUILogin
import com.tencent.qcloud.tuicore.interfaces.TUICallback
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/5/31 4:12 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：密码登录
 */
@Route(path = ARoutUtils.LoginActivityURL)
class LoginActivity : BaseActivity<ActivityLoginBinding>(), View.OnClickListener {
    @Autowired(name = ARoutUtils.AROUT_TAG)
    @JvmField
    var mTagARouter: AroutBean? = null

    private var timer: TimerUnit? = null
    private var mOpenId: String? = null
    private var mThreeName: String? = null
    private var mThreeLogo: String? = null
    private var mCode: String? = null
    private val serviceViewModel: ServiceViewModel by viewModel()
    private val mEditorViewModel by viewModels<EditorViewModel>()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())

    override fun getLayoutRes() = R.layout.activity_login
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            vm = mEditorViewModel
            initSingleClickListener(
                tvAgree, ivWechatLogin, ivQqLogin, ivAliLogin, tvCode, btnLogin,
                tvForgotPwdLogin, tvRegisterLogin
            )
            StatusBarUtil.setHeightAndPadding(this@LoginActivity, titleBar)
            titleBar.onClickBackIcon { finish() }

            mBinding.tvAgree.setText(
                createSpanTexts(),
                SpanTextView.SpanClickListener { position ->
                    ConsealWebActivity.openUrl(this@LoginActivity, "0")
                })

        }
    }

    private fun threeLanding(threedLoginReqBody: ThreedLoginReqBody) {
        startLoading()
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.threeLanding(threedLoginReqBody) }.await()
            parseThreeLandingResult(result)
        }

    }

    private fun parseThreeLandingResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<UserInfo> { code, data, message, result ->
                login(data)
            }
            onBizError<TokenBean> { code, message, data ->

            }
        }
    }

    private fun loginByCode() {
        startLoading()
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async {
                    serviceViewModel.loginByCode(
                        LoginByCodeReqBody(
                            mEditorViewModel.obMobile.get()!!, mEditorViewModel.obPassword.get()!!
                        )
                    )
                }.await()
            parseLoginByCodeResult(result)
        }

    }

    private fun parseLoginByCodeResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<UserInfo> { code, data, message, result ->
                login(data)
            }
            onBizError<Any> { code, message, data ->

            }
        }
    }

    private fun showSwipecaptDialog(phone: String) {
        val swipeCatpchaDialog =
            SwipeCatpchaDialog(this, true, true, object : OnDialogSureListener {
                override fun onSureClick(content: String?) {
                    val sendCode = sendCode(phone)
                    sendCode(SendCodeBody(phone, sendCode))
                }
            })
        swipeCatpchaDialog.show()
    }


    private fun sendCode(phone: SendCodeBody) {
        startLoading()
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async {
                    serviceViewModel.sendCode(phone)
                }.await()
            parseSendCodeResult(result)
        }

    }

    private fun parseSendCodeResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<Any> { code, data, message, result ->
                if (timer == null) {
                    timer = TimerUnit(mBinding.tvCode)
                }
                timer?.startTime()
                message?.let { message ->
                    showToast(this@LoginActivity, message)
                }
            }
            onBizError<Any> { code, message, data ->

            }
        }
    }

    override fun initConfig() {
        super.initConfig()
        OfflineMessageDispatcher.updateBadge(this@LoginActivity, 0)

    }

    private fun login(res: UserInfo?) {
        res?.let {
            YgxUtilsKt.setAppToken(it.token, it.refreshtoken, it.id)
            //强行登入 忽略IM登录
//            UserDbHelper.insertUserInfo(this@LoginActivity, res)

            // 在用户 UI 点击登录的时候调用
            TUILogin.login(
                this@LoginActivity,
                GenerateTestUserSig.SDKAPPID,
                it.txaccid,
                it.txaccidpassword,
                object : TUICallback() {
                    override fun onError(code: Int, desc: String) {
//                        loadFinished()
                        LogUtils.e("onError")
                    }

                    override fun onSuccess() {
//                        loadFinished()
                        UserDbHelper.insertUserInfo(this@LoginActivity, res)
                        LogUtils.e("onSuccess")
                        YgxUtilsKt.sendMessgeToSelf(it.txaccid, it.phone)

                        mTagARouter?.apply {
                            YgxAroutPageKt.LoginToTarget(mTagARouter, res)
                        }
//                        val comAndSpuList = res.comAndSpuList
//                        if (comAndSpuList.isNullOrEmpty()) {
//                            ARouter.getInstance().build(ARoutUtils.IndustrySelectedActivity)
//                                .withParcelable("userinfo", res)
//                                .navigation()
//                        }
                        finish()
                    }
                })
        }
    }

    override fun initData() {
        super.initData()
        //一键登录页面进入，发消息关闭一键登录 避免一键登录跳转页面闪动
        LiveEventBus
            .get(LiveEventUtils.FINISH_ONEKEYLOGINACTIVITY_KEY, String::class.java)
            .post("1")
        //三方登录没有绑定手机号的消息
        LiveEventBus
            .get(LiveEventUtils.THREELANDING_KEY, String::class.java)
            .observe(this) { s ->
                s?.let {
                    if (s == "202") {
                        ARouter.getInstance().build(ARoutUtils.BindPhoneActivity)
                            .withString("openId", mOpenId)
                            .withString("code", mCode)
                            .withString("name", mThreeName)
                            .withString("logo", mThreeLogo)
                            .navigation()
                    }
                }
            }
        //收到密码登录页面消息，关闭当前页面
        LiveEventBus
            .get(LiveEventUtils.FINISH_LOGINACTIVITY_KEY, String::class.java)
            .observe(this) {
                finish()
            }

        LiveEventBus.get(
            ThreeLandingEvent::class.java,
        ).observe(this) { s ->
            if (s != null && s.tag == 0) {//微信
//                val openid = YgxUtils.encodeWithUtf8(s.openid)
                val openid = s.openid
                mOpenId = openid
                mCode = "0"
                mThreeName = s.name
                mThreeLogo = s.headerUrl
                val threedLoginReqBody = ThreedLoginReqBody(openid, "0", s.name, s.headerUrl)
                threeLanding(threedLoginReqBody)
            }
        }
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.tv_forgot_pwd_login -> {
                ARouter.getInstance().build(ARoutUtils.LoginByPassWordActivity).navigation()
                finish()
            }

            R.id.tv_register_login -> {
                ARouter.getInstance().build(ARoutUtils.RegistActivityURL).navigation()
                finish()
            }

            R.id.btn_login -> {
                loginByCode()
            }

            R.id.tv_agree -> {
                mBinding.cbBox.isChecked = !mBinding.cbBox.isChecked
            }

            R.id.iv_wechat_login -> {
                if (mEditorViewModel.obIsAgree.get() == true) {
                    if (YgxNetUtilsKt.isWechatInstalled()) {
                        startLoading()
                        ShareUtils.get().login(
                            this@LoginActivity, ShareUtils.WEIXIN
                        )
                    } else {
                        showToast("您手机暂时未安装微信")
                    }
                } else {
                    showToast("同意服务条款才可以登录")
                }
            }

            R.id.iv_qq_login -> {
                if (mEditorViewModel.obIsAgree.get() == true) {
                    if (YgxNetUtilsKt.isQQInstalled()) {
                        startLoading()
                        ShareUtils.get().login(
                            this@LoginActivity, ShareUtils.QQ
                        ).setOnQqCallBackListener({ it, openId, nikeName, logo ->
                            mThreeName = nikeName
                            mThreeLogo = logo
                            LogUtils.e("openid  $openId")
                            if (!openId.isNullOrEmpty()) {
                                val threedLoginReqBody =
                                    ThreedLoginReqBody(openId, "1", nikeName, logo)
                                mOpenId = openId
                                mCode = "1"
                                threeLanding(threedLoginReqBody)
                            }
                        }, {
                            loadFinished()
                        })
                    } else {
                        showToast("您手机暂时未安装QQ")
                    }
                } else {
                    showToast("同意服务条款才可以登录")
                }

            }

            R.id.iv_ali_login -> {
                if (mEditorViewModel.obIsAgree.get() == true) {
                    if (YgxNetUtilsKt.isAliInstalled(this@LoginActivity)) {
                        startLoading()
                        val shareUtils = ShareUtils.get().login(this@LoginActivity, ShareUtils.ALI)
                        shareUtils.setOnAliCallBackListener({ userId, openId ->
                            if (!userId.isNullOrEmpty()) {
                                val threedLoginReqBody = ThreedLoginReqBody(userId, "2")
                                mOpenId = userId
                                mCode = "2"
                                threeLanding(threedLoginReqBody)
                            }
                        }, { loadFinished() })
                    } else {
                        showToast("您手机暂时未安装支付宝")
                    }
                } else {
                    showToast("同意服务条款才可以登录")
                }
            }

            R.id.tv_code -> {
                val phone = mEditorViewModel.obMobile.get()
                if (phone.isNullOrEmpty() || phone.length < 11) {
                    showToast(this@LoginActivity, "请输入11位手机号")
                } else {
                    if (mEditorViewModel.obIsAgree.get() == true) {
                        showSwipecaptDialog(phone)

                    } else {
                        showToast(this@LoginActivity, "请同意服务条款")
                    }
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data != null) {
            //QQ回调
            ShareUtils.get().onQqActivityResult(requestCode, resultCode, data)
        }
    }

    private fun createSpanTexts(): List<SpanTextView.BaseSpanModel>? {
        val spanModels: MutableList<SpanTextView.BaseSpanModel> = ArrayList()
        var textSpanModel = SpanTextView.TextSpanModel()
        textSpanModel.content = "我已经阅读并同意"
        spanModels.add(textSpanModel)
        var spanModel = SpanTextView.ClickSpanModel()
        spanModel.content = "《亨富然隐私政策》"
        spanModels.add(spanModel)
//        textSpanModel = SpanTextView.TextSpanModel()
//        textSpanModel.content = "，未注册的手机号将自动创建亨富然账号"
//        spanModels.add(textSpanModel)
//        spanModel = ClickSpanModel()
//        spanModel.content = "Lucy"
//        spanModels.add(spanModel)
        return spanModels
    }

    override fun initEvents() {
        super.initEvents()
        mBinding.etPhone.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence,
                start: Int,
                count: Int,
                after: Int
            ) {
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
//                    etPhone.paint.isFakeBoldText = !TextUtils.isEmpty(s)
                if (s.length == 11) {
                    mBinding.etCode.requestFocus()
                }

            }

            override fun afterTextChanged(s: Editable) {
            }
        })
    }

}